<template>
  <div>
    <div class="select-box">
      <el-form :inline="true" :model="selectData" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="selectData.title" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="详情">
          <el-input v-model="selectData.introduce" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="comList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="introduce" label="详情" />
    </el-table>
    <el-pagination layout="prev, pager, next" :page-size="selectData.pagesize" :total="selectData.count"
      @current-change="currentChange" @size-change="sizeChange" />
  </div>
</template>

<script setup lang="ts">
import { getGoodsList } from '@/request/api';
import { ListInit, selectDataInit } from '@/type/goods';
import { computed, reactive, ref, watch } from 'vue';

const selectData = reactive<selectDataInit>({
  title: '',
  introduce: '',
  page: 1,
  count: 0,
  pagesize: 5
})
const list = ref<ListInit[]>([]);
const getGoods = () => {
  getGoodsList().then(res => {
    list.value = res.data;
    selectData.count = list.value.length;
  })
}
getGoods()
const currentChange = (page: number) => {
  selectData.page = page;
}
const sizeChange = (pagesize: number) => {
  selectData.pagesize = pagesize;
}
const comList = computed(() => {
  return list.value.slice((selectData.page - 1) * selectData.pagesize, selectData.page * selectData.pagesize);
})
watch([() => selectData.title, () => selectData.introduce], () => {
  if (!selectData.title && !selectData.introduce) {
    getGoods()
  }
})
const onSubmit = () => {
  console.log('submit');
  let arr: ListInit[] = []
  if (selectData.title || selectData.introduce) {
    if (selectData.title) {
      arr = list.value.filter((value) => {
        return value.title.indexOf(selectData.title) !== -1;
      })
    } else if (selectData.introduce) {
      arr = list.value.filter((value) => {
        return value.introduce.indexOf(selectData.introduce) !== -1;
      })
    } else {
      arr = list.value;
    }
    list.value = arr;
    selectData.count = arr.length;
  }
}
</script>

<style lang="scss" scoped>
</style>